package com.knife.news.logic.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.knife.news.logic.UserService;
import com.knife.news.object.User;

public class UserServiceImpl extends DAOSupportService implements UserService {

	private static UserServiceImpl userDAO = new UserServiceImpl();

	public static UserServiceImpl getInstance() {
		return userDAO;
	}

	public boolean saveUser(User user) {
		com.knife.news.model.User auser=new com.knife.news.model.User();
		user.setId(auser.getId());
		auser.setUser(user);
		return this.dao.save(auser);
	}

	public boolean updateUser(User user) {
		com.knife.news.model.User auser=new com.knife.news.model.User();
		auser.setUser(user);
		return this.dao.update(auser);
	}

	public boolean deleteUser(User user) {
		com.knife.news.model.User auser=new com.knife.news.model.User();
		auser.setUser(user);
		return this.dao.del(auser);
	}

	public User getUserById(String id) {
		com.knife.news.model.User auser=(com.knife.news.model.User) this.dao.get(com.knife.news.model.User.class, id);
		if(auser!=null){
			return new User(auser);
		}else{
			return null;
		}
	}

	public User getUserByName(String username) {
		com.knife.news.model.User auser=(com.knife.news.model.User) this.dao.getBy(com.knife.news.model.User.class, "k_username", username);
		if(auser!=null){
			return new User(auser);
		}else{
			return null;
		}
	}

	public List<User> getAllUsers() {
		return changeListType(this.dao.query(com.knife.news.model.User.class, "k_username!=''"));
	}

	public List<User> getUsersBySql(String sql) {
		return changeListType(dao.query(com.knife.news.model.User.class, sql));
	}
	
	public List<User> getUsersBySql(String sql, Collection<Object> paras, int begin, int end) {
		return changeListType(this.dao.query(com.knife.news.model.User.class,sql,paras,begin,end));
	}
	
	public int getSum(int popedom){
		int sum=0;
		String sql = "select count(*) from k_user where id!=''";
		Collection<Object> paras=new ArrayList<Object>();
		if(popedom >= 0) {
			paras.add(popedom);
			sql += " and k_popedom=?";
		}
		sum=Integer.parseInt(this.dao.uniqueResult(sql,paras).toString());
		return sum;
	}
	
	public List<User> changeListType(List<Object> users){
		List<User> results = new ArrayList<User>();
		if(users!=null){
			for (Object newobj : users) {
				com.knife.news.model.User bnews = (com.knife.news.model.User) newobj;
				User auser=new User(bnews);
				results.add(auser);
			}
		}
		return results;	
	}
}
